package com.itheima.servlets.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
    登录安全认证过滤器
        未登录系统，不得访问工程的资源
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //session是否有登录者信息
        //向下转型
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取统一资源标识
        String uri = req.getRequestURI();
        //判断是否符合条件
        if ("/day08_web_student/index.jsp".equals(uri) || "/day08_web_student/login.jsp".equals(uri) || "/day08_web_student/UserServlet/login".equals(uri)) {
            //符合就放行
            filterChain.doFilter(req, resp);
        } else {
            //不符合 就执行下面操作
            //获取session对象
            HttpSession session = req.getSession();
            //从session中获取登录者信息
            Object user = session.getAttribute("user");
            //判断登录者信息是否为空
            if (user != null) {
                //不为空 登录成功 放行
                filterChain.doFilter(req, resp);
            } else {
                //为空 登录失败 返回登录页面
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
